from itertools import cycle
from string import split

class Pattern( object ):
	def __init__(self , pattern ):		
		bars = split( pattern ,"|" )
		self.bars = []
		for bar in bars:
			self.bars.append(  list ( bar ))  
	def calculateBeatLength( self , bartime , numbeats ):
		beatlen= float(bartime)/float(numbeats)
		#print bartime,numbeats,beatlen
		return beatlen
	def renderPattern( self , track , instrument , starttime , endtime , bartime , velocityfun , timingmodfun ):		
		curtime = starttime
		baritr = cycle( self.bars )
		curbar = baritr.next()
		beatlen = self.calculateBeatLength( bartime , len( curbar ))
		curbaritr = curbar.__iter__()
		while curtime < endtime:
				try:
					beat = curbaritr.next()
				except:
					curbar = baritr.next()
					beatlen = self.calculateBeatLength( bartime , len( curbar ))
					curbaritr = curbar.__iter__()
					beat = curbaritr.next()
				if beat == "x":					
					track.addNote( curtime + timingmodfun.getMod()   ,   instrument.getNote() , instrument.getDuration(), velocityfun.NormalVelocity() )
				elif beat == "X":
					track.addNote( curtime + timingmodfun.getMod()  ,   instrument.getNote() , instrument.getDuration(), velocityfun.NormalVelocity() )
				else:
					pass
				curtime += beatlen

if __name__ == '__main__':
	import Velocities 
	import Instruments
	import Events
	import Timings
	e = Events.SongEventList()		
	p = Pattern( "X---Xx--" )
	e["one"].setChannel( 9 )
	e.setTempo( int(60000000.00 / 100) )
	p.renderPattern( e["one"] ,  Instruments.GMDrumInstrument( "Electric Snare" ) , 0 , 4500 , 240 , Velocities.StandardVelocity( 120 , 80 , 10 ) , Timings.BehindTheBeat( 5 ) )
	p = Pattern( "--X---X-" )	
	p.renderPattern( e["one"] ,  Instruments.GMDrumInstrument( "Bass Drum" ) , 0 , 4500 , 240 , Velocities.StandardVelocity( 120 , 80 , 10 ) , Timings.StandardTiming( .05 ) )
	e.makeMidiFile( "rhythmtest.mid")
	
